package com.xkcyy.one.service;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xkcyy.one.entity.Training;
import com.xkcyy.one.entity.TrainingSession;
import com.xkcyy.one.exception.BusinessException;
import com.xkcyy.one.mapper.TrainingMapper;
import com.xkcyy.one.mapper.TrainingSessionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 训练会话服务类
 */
@Service
public class TrainingSessionService {
    
    private final TrainingSessionMapper trainingSessionMapper;
    private final TrainingMapper trainingMapper;
    
    @Autowired
    public TrainingSessionService(TrainingSessionMapper trainingSessionMapper, TrainingMapper trainingMapper) {
        this.trainingSessionMapper = trainingSessionMapper;
        this.trainingMapper = trainingMapper;
    }
    
    /**
     * 根据训练ID获取会话列表
     *
     * @param trainingId 训练ID
     * @return 会话列表
     */
    public List<TrainingSession> getSessionsByTrainingId(Long trainingId) {
        // 检查训练是否存在
        if (trainingMapper.selectById(trainingId) == null) {
            throw new BusinessException("训练不存在，ID: " + trainingId);
        }
        
        LambdaQueryWrapper<TrainingSession> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TrainingSession::getTrainingId, trainingId);
        queryWrapper.orderByAsc(TrainingSession::getIteration);
        return trainingSessionMapper.selectList(queryWrapper);
    }
    
    /**
     * 根据ID获取会话
     *
     * @param id 会话ID
     * @return 会话
     */
    public TrainingSession getSessionById(Long id) {
        TrainingSession session = trainingSessionMapper.selectById(id);
        if (session == null) {
            throw new BusinessException("训练会话不存在，ID: " + id);
        }
        return session;
    }
    
    /**
     * 创建会话 - 内部方法，只供TrainingService调用
     *
     * @param session 会话
     * @return 创建后的会话
     */
    @Transactional
    protected TrainingSession createSession(TrainingSession session) {
        // 检查训练是否存在
        Training training = trainingMapper.selectById(session.getTrainingId());
        if (training == null) {
            throw new BusinessException("训练不存在，ID: " + session.getTrainingId());
        }
        session.setId(IdUtil.getSnowflakeNextId());
        // 设置会话迭代序号
        session.setIteration(training.getCurrentIteration() + 1);
        
        // 设置开始时间
        session.setStartTime(LocalDateTime.now());
        
        // 设置状态
        session.setStatus("RUNNING");
        
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        session.setCreateTime(now);
        session.setUpdateTime(now);
        
        // 插入会话
        trainingSessionMapper.insert(session);
        
        // 更新训练的当前迭代次数
        training.setCurrentIteration(session.getIteration());
        training.setStatus("RUNNING");
        training.setUpdateTime(now);
        trainingMapper.updateById(training);
        
        return session;
    }
    
    /**
     * 完成会话 - 内部方法，只供TrainingService调用
     *
     * @param id            会话ID
     * @param accuracy      准确度
     * @param responseTime  响应时间
     * @param efficiency    效率
     * @return 更新后的会话
     */
    @Transactional
    protected TrainingSession completeSession(Long id, Float accuracy, Float responseTime, Float efficiency) {
        TrainingSession session = trainingSessionMapper.selectById(id);
        if (session == null) {
            throw new BusinessException("训练会话不存在，ID: " + id);
        }
        
        // 设置结束时间
        session.setEndTime(LocalDateTime.now());
        
        // 设置性能指标
        session.setAccuracy(accuracy);
        session.setResponseTime(responseTime);
        session.setPromptEfficiency(efficiency);
        
        // 设置状态
        session.setStatus("COMPLETED");
        
        // 设置更新时间
        session.setUpdateTime(LocalDateTime.now());
        
        // 更新会话
        trainingSessionMapper.updateById(session);
        
        // 获取训练
        Training training = trainingMapper.selectById(session.getTrainingId());
        
        // 检查是否已达到最大迭代次数
        if (training.getCurrentIteration() >= training.getMaxIterations()) {
            // 更新训练状态为已完成
            training.setStatus("COMPLETED");
            training.setUpdateTime(LocalDateTime.now());
            trainingMapper.updateById(training);
        }
        
        return session;
    }
    
    /**
     * 更新会话的优化提示词 - 内部方法，只供TrainingService调用
     *
     * @param id     会话ID
     * @param prompt 优化后的提示词
     * @return 更新后的会话
     */
    @Transactional
    protected TrainingSession updateSessionPrompt(Long id, String prompt) {
        TrainingSession session = trainingSessionMapper.selectById(id);
        if (session == null) {
            throw new BusinessException("训练会话不存在，ID: " + id);
        }
        
        // 设置提示词
        session.setPrompt(prompt);
        
        // 设置更新时间
        session.setUpdateTime(LocalDateTime.now());
        
        // 更新会话
        trainingSessionMapper.updateById(session);
        
        // 更新训练的优化提示词
        Training training = trainingMapper.selectById(session.getTrainingId());
        training.setOptimizedPrompt(prompt);
        training.setUpdateTime(LocalDateTime.now());
        trainingMapper.updateById(training);
        
        return session;
    }
} 